const { typesModel } = require('./models/typesModel');

//根据ID保险分类
module.exports.getTypesById = async params => {
    // return await typesModel.find(params);
    const data = await typesModel.aggregate([
        {
            $lookup: {
                from: 'insures',
                localField: '_id',
                foreignField: 'typesId',
                as: 'insuresData'
            }
        },
    ]);
    return data.filter(item => item._id == params._id);
}

//获取所有保险分类
module.exports.getTypes = async ({ value = '' }) => {
    // 模糊查询
    const types = await typesModel
        .find({ isDel: false, name: { $regex: value, $options: '$i' } })
    return { types };
}
module.exports.getTypesInsures = async params => {
    const data = await typesModel.aggregate([
        {
            $lookup: {
                from: 'insures',
                localField: '_id',
                foreignField: 'typesId',
                as: 'insuresData'
            }
        },
    ]);
    return data.filter(item => !item.isDel);
}

//新增保险分类
module.exports.addTypes = async params => {
    return await typesModel.create(params);
}

//修改保险分类
module.exports.modifyTypes = async params => {
    return await typesModel.updateOne({ _id: params._id }, params);
}

//删除保险分类
module.exports.delTypes = async params => {
    return await typesModel.updateOne(params, { isDel: true });
}
module.exports.isDel = async params => {
    const data = await typesModel.aggregate([
        {
            $lookup: {
                from: 'insures',
                localField: '_id',
                foreignField: 'typesId',
                as: 'insuresData'
            }
        },
    ]);
    return data.filter(item => item._id == params._id)[0].insuresData.filter(item => !item.isDel).length;
}